When you call empty()
or is_empty()
, it clearly communicates the code’s intention, which is to check if the collection is
empty. Using size() == 0
for this purpose is less direct and makes the code slightly more complex.
Moreover, depending on the implementation, the size()
, length()
, or count()
methods can have a time
complexity of O(n)
where n
is the number of elements in the collection. On the other hand, empty()
and
is_empty()
simply check if there is at least one element in the collection, which is a constant time operation, O(1)
.
void fun(const std::vector<int> &myVector) {
if (myVector.size() == 0) { // Noncompliant
// do something
}
}
Prefer using empty()
or is_empty()
to test for emptiness over size()
, length()
, or
count()
.
void fun(const std::vector<int> &myVector) {
if (myVector.empty()) {
// do something
}
}